package apps

var RootTpl = `
package cmd

import (
    "context"
    "fmt"
    "github.com/spf13/cobra"
    "log"
    "net/http"
    "os"
    "os/signal"
    "time"
    "{{.App}}/bff/internal/router"
    "{{.App}}/pkg/storage/chain"
    "{{.App}}/pkg/storage/conf"
    "{{.App}}/pkg/storage/db"
    "{{.App}}/pkg/storage/verify"
    "{{.App}}/pkg/storage/redis"
)

var rootCmd = &cobra.Command{
    Use:   "bff",
    Short: "A brief description of your application",
    Long:  "a bff test",
    Run: func(cmd *cobra.Command, args []string) {
        BffRun()
    },
}

func Execute() {
    err := rootCmd.Execute()
    if err != nil {
        os.Exit(1)
    }
}

var port string

func init() {
    rootCmd.Flags().StringVar(&port, "port", ":8080", "端口")
}

func BffRun() {
    conf.Init()
    db.Init()
    verify.Init()
	redis.Init()
    if conf.Cfg.Chain.Enable == true {
        err := chain.JaegerInit()
        if err != nil {
            fmt.Println("调用链错误")
            os.Exit(1)
        }
    }
    r := router.Router()

    srv := &http.Server{
        Addr:    port,
        Handler: r,
    }

    go func() {
        // 服务连接
        if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
            log.Fatalf("listen: %s\n", err)
        }
    }()
    quit := make(chan os.Signal, 1)
    signal.Notify(quit, os.Interrupt)
    <-quit
    log.Println("Shutdown Server ...")

    ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
    defer cancel()
    if err := srv.Shutdown(ctx); err != nil {
        log.Fatal("Server Shutdown:", err)
    }
    log.Println("Server exiting")
}
`
